﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.Security;
using ActionModel.Utility;
using ActionModel.WebModel;

namespace FilesArranger
{
	/// <summary>
	/// AjaxLogin 的摘要说明
	/// </summary>
	public class AjaxLogin : MultiActionAjaxHandler
	{
		protected override void RegisterAction()
		{
			ActionDict.Add("login", new Action(CheckUserLogin));
			ActionDict.Add("logout", new Action(CheckUserLogout));
		}

		protected override void DoProcessRequest(HttpContext context)
		{
			
		}


		void CheckUserLogin()
		{
			string RootFullPath = Request.ApplicationPath == "/" ? Request.ApplicationPath : Request.ApplicationPath + "/";
			string username = Request["username"];
			string password = Request["password"];
			UserEntry user = new UserEntry();
			bool checkResult = false;
			if (username == "admin" && password == "adminer")
			{
				checkResult = true;
			}
			if (username == "test" && password == "test")
			{
				RootFullPath += "test/";
				if (!Directory.Exists(Request.MapPath(RootFullPath)))
				{
					Directory.CreateDirectory(Request.MapPath(RootFullPath));
				}
				checkResult = true;
			}
			user.UserName = username;
			user.PassWord = password;
			user.UserRootPath = RootFullPath;
			if (checkResult)
			{
				//string physicalPath = MapPath(CurentUser.UserRootPath);
				//DirectoryInfo rootDirectory = new DirectoryInfo(physicalPath);
				//int preLength = MapPath("/").Length - 1;
				//TreeNode rootNode = FilesArrangerTreeToDo.CastToTreeNode(rootDirectory);
				//TreeNode[] rootNodes = new TreeNode[] { rootNode };
				FormsAuthentication.SetAuthCookie(username, false);
				JsonResult.WriteSuccess();
			}
			else
			{
				JsonResult.WriteError("Login failed");
			}
		}

		void CheckUserLogout()
		{
			FormsAuthentication.SignOut();
			JsonResult.WriteSuccess();
		}

		public override bool IsReusable
		{
			get { throw new NotImplementedException(); }
		}
	}
}